/*
  学习目标：Redux的基本使用-subscribe监听仓库的变化
*/

import { createStore } from "redux";

const store = createStore(function (
  state = { count: 0, msg: "React" },
  action
) {
  console.warn("进入仓库了  ----->  ", action);

  if (action.type === "add") {
    return {
      ...state,
      count: state.count + 1,
    };
  }

  if (action.type === "des") {
    return {
      ...state,
      count: state.count - 1,
    };
  }
  return state;
});

// 1 使用subscribe开启监听仓库
// 语法上: const 关闭监听的函数 = store.subscribe(回调函数) , 回调函数中, 可以获取到更新后的值

store.dispatch({ type: "add" });
store.dispatch({ type: "des" });

// subscribe要在开启后, dispatch才能触发, 开启前dispatch不触发
const unFn = store.subscribe(() => {
  console.log("store改变了", store.getState());
});

store.dispatch({ type: "add" });

// 2 关闭监听
// 调用unFn就是关闭监听
unFn();
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
